<template>
  <div class="workorder-apply-page">
    <div class="banner">
      <div class="banner-content">
        <img class="logo" src="@/assets/photoes/logo.jpg" alt="logo" />
        <div class="banner-title">铁岭电网无人机管理平台</div>
      </div>
      <img class="banner-bg" src="@/assets/background.png" alt="banner" />
    </div>
    <div class="form-section">
      <div class="back-btn-section">
        <el-button class="back-btn" :icon="ArrowLeft" @click="goBack">返回</el-button>
      </div>
      <h2 class="form-title">
        {{ isEditMode.value ? "修改无人机作业申请" : "无人机作业申请表" }}
      </h2>
      <el-form :model="form" ref="formRef" label-width="120px" :rules="rules" class="apply-form">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="作业地点" prop="address">
          <el-input v-model="form.address" placeholder="请输入作业地点" />
        </el-form-item>
        <el-form-item label="预计作业时间" prop="estimatedHomeworkTime">
          <el-date-picker v-model="form.estimatedHomeworkTime" type="datetime" placeholder="选择日期时间" style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联项目信息" prop="projectInfo">
          <el-input v-model="form.projectInfo" placeholder="请输入关联项目信息" />
        </el-form-item>
        <el-form-item label="项目编号/名称" prop="projectInfo">
          <el-input v-model="form.projectInfo" placeholder="请输入项目编号或名称" />
        </el-form-item>
        <el-form-item label="选择无人机" prop="uavId">
          <el-select v-model="form.uavId" placeholder="请选择无人机">
            <el-option v-for="uav in uavList" :key="uav.id" :label="uav.uavName" :value="uav.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDescription">
          <el-input v-model="form.taskDescription" type="textarea" :rows="5" placeholder="请描述任务内容、要求或其他特殊说明等" />
        </el-form-item>
        <el-form-item label="附件上传" prop="file1">
          <el-upload class="upload-demo" drag :action="null" :auto-upload="false" :show-file-list="true"
            :on-change="handleFileChange" :before-upload="beforeFileUpload" :file-list="fileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
          <p class="upload-tip">支持常见文档格式，单个文件大小不超过10MB</p>
        </el-form-item>
        <div class="form-btns">
          <el-button type="primary" @click="onSubmit" :disabled="!canSubmit">{{
            isEditMode.value ? "保存修改" : "提交申请"
          }}</el-button>
          <el-button @click="onReset">{{
            isEditMode.value ? "重置修改" : "重置"
          }}</el-button>
        </div>
      </el-form>
    </div>
    <!-- <footer class="footer">
      <div class="footer-top">
        <div class="footer-logo">
          <img src="../../assets/photoes/logo.jpg" alt="logo" />
          <span class="system-name">铁岭电网无人机管理平台</span>
        </div>
        <div class="contact-info">
          <div class="contact-item">
            <img src="../../assets/photoes/home/phone.png" class="size-img" />
            <p>010-62092911</p>
          </div>
          <div class="contact-item">
            <img src="../../assets/photoes/home/message.png" class="size-img" />
            <p>ZCQS@BNU.EDU.CN</p>
          </div>
        </div>
        <div class="qrcode">
          <img src="../../assets/photoes/home/qrcode.png" alt="qrcode" />
          <p>扫一扫关注我们</p>
        </div>
      </div>
      <div class="footer-bottom">
        <p>
          京公网安备 11010502031377 Copyright © 2005 ALL RIGHTS RESERVED
          XXXXX有限公司版权所有
        </p>
      </div>
    </footer> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const formRef = ref();
const isEditMode = ref(false);
const editId = ref("");

const form = reactive({
  taskName: "",
  address: "",
  estimatedHomeworkTime: "",
  priority: "",
  projectInfo: "",
  taskDescription: "",
  uavId: "",
  file1: null,
  createUser: "员工",
});
const rules = {
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入作业地点", trigger: "blur" }],
  estimatedHomeworkTime: [
    { required: true, message: "请选择作业时间", trigger: "change" },
  ],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
  projectInfo: [{ required: true, message: "请输入项目信息", trigger: "blur" }],
  uavId: [{ required: true, message: "请选择无人机", trigger: "change" }],
};
const uavList = ref([]);
const fileList = ref([]);

function handleFileChange(file, fileListArr) {
  form.file1 = file.raw;
  fileList.value = fileListArr;
}

// 文件上传前验证
function beforeFileUpload(file) {
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isLt10M) {
    ElMessage.error("上传文件大小不能超过 10MB!");
    return false;
  }

  return true;
}

// 计算属性：是否可以提交
const canSubmit = computed(() => {
  // 检查是否有文件验证错误
  if (fileList.value.some((file) => file.status === "fail")) {
    return false;
  }

  return true;
});

async function onSubmit() {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    const formData = new FormData();
    formData.append("taskName", form.taskName);
    formData.append("address", form.address);
    formData.append("estimatedHomeworkTime", form.estimatedHomeworkTime);
    formData.append("priority", form.priority);
    formData.append("projectInfo", form.projectInfo);
    formData.append("taskDescription", form.taskDescription);
    formData.append("uavId", form.uavId);
    formData.append("createUser", form.createUser);
    if (form.file1) formData.append("file1", form.file1);

    try {
      let res;
      if (isEditMode.value) {
        // 修改模式
        formData.append("uavld", editId.value);
        res = await axios.post(
          "/tielingpowergriduavservice/task/update",
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
          }
        );
      } else {
        // 新增模式
        res = await axios.post(
          "/tielingpowergriduavservice/task/add",
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
          }
        );
      }

      if (res.data && res.data.code === 200) {
        ElMessage.success(isEditMode.value ? "修改成功" : "提交成功");
        if (!isEditMode.value) {
          // 新增成功后跳转到工单管理页面
          router.push("/workorder");
        } else {
          // 修改成功后返回工单管理页面
          router.push("/workorder");
        }
      } else {
        ElMessage.error(
          res.data?.message || (isEditMode.value ? "修改失败" : "提交失败")
        );
      }
    } catch (e) {
      ElMessage.error(isEditMode.value ? "修改异常" : "提交异常");
    }
  });
}
function onReset() {
  form.taskName = "";
  form.address = "";
  form.estimatedHomeworkTime = "";
  form.priority = "";
  form.projectInfo = "";
  form.taskDescription = "";
  form.uavId = "";
  form.file1 = null;
  fileList.value = [];
}
function goBack() {
  router.back();
}
onMounted(async () => {
  // 获取无人机列表
  const res = await axios.get("/tielingpowergriduavservice/uav/list");
  if (res.data && res.data.code === 200) {
    uavList.value = res.data.data || [];
  }

  // 检查是否为修改模式
  if (route.query.mode === "edit") {
    isEditMode.value = true;
    editId.value = route.query.id;

    // 数据回显
    form.taskName = route.query.taskName || "";
    form.address = route.query.address || "";
    form.estimatedHomeworkTime = route.query.estimatedHomeworkTime || "";
    form.priority = route.query.priority || "";
    form.projectInfo = route.query.projectInfo || "";
    form.taskDescription = route.query.taskDescription || "";
    form.uavId = route.query.uavId || "";
  }
});
</script>

<style scoped>
.workorder-apply-page {
  min-height: 100vh;
  background: #f8fafd;
  display: flex;
  flex-direction: column;
}

.banner {
  position: relative;
  width: 100%;
  height: 220px;
  background: #199893;
  overflow: hidden;
  display: flex;
  align-items: flex-end;
}

.banner-content {
  position: absolute;
  left: 60px;
  top: 40px;
  z-index: 2;
  display: flex;
  align-items: center;
}

.logo {
  width: 200px;
  height: 50px;
  margin-right: 18px;
}

.banner-title {
  color: #fff;
  font-size: 28px;
  font-weight: bold;
  letter-spacing: 2px;
}

.banner-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.7;
}

.form-section {
  max-width: 100%;
  margin: 60px 30px 0 30px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(25, 152, 147, 0.08);
  padding: 48px 36px 36px 36px;
  min-height: 500px;
}

.form-title {
  text-align: center;
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 32px;
  letter-spacing: 2px;
}

.apply-form {
  max-width: 900px;
  margin: 0 auto;
}

.form-btns {
  display: flex;
  justify-content: center;
  gap: 32px;
  margin-top: 32px;
}

.back-btn-section {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 18px;
}

.back-btn {
  font-size: 16px;
  padding: 10px 28px;
  border-radius: 22px;
  background: linear-gradient(90deg, #199893 0%, #4fd1c5 100%);
  color: #fff;
  box-shadow: 0 2px 12px rgba(25, 152, 147, 0.1);
  border: none;
  transition: background 0.2s, box-shadow 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn:hover {
  background: linear-gradient(90deg, #12706b 0%, #199893 100%);
  box-shadow: 0 4px 16px rgba(25, 152, 147, 0.18);
}

.footer {
  background: #2c3e50;
  color: #e0e0e0;
  padding: 40px 0 20px;
  margin-top: 100px;
}

.footer-top {
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #3d5a7c;
}

.footer-logo {
  display: flex;
  align-items: center;
}

.footer-logo img {
  width: auto;
  height: 50px;
  margin-right: 12px;
}

.footer .system-name {
  color: #ffffff;
  font-size: 20px;
  font-weight: 600;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.contact-item {
  display: flex;
  align-items: center;
}

.contact-item p {
  color: #e0e0e0;
  font-size: 15px;
  margin: 0;
}

.size-img {
  margin-right: 12px;
  width: 22px;
  height: 22px;
}

.qrcode {
  text-align: center;
}

.qrcode img {
  width: 120px;
  height: 120px;
  margin-bottom: 12px;
  border: 4px solid #ffffff;
  border-radius: 8px;
}

.qrcode p {
  color: #e0e0e0;
  font-size: 15px;
  margin: 0;
}

.footer-bottom {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #3d5a7c;
}

.footer-bottom p {
  color: #b0b0b0;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 15px;
}
</style>
